import { createStore } from 'redux'

// state 初始值
const initState = {
  list: [],
  type: 'all'
}

// reducer 函数 (state, action)=> newState
function reducer(state = initState, action) {
  console.warn('Redux Logger', { oldState: state, action })
  switch (action.type) {
    case 'setTodos':
      return {
        ...state,
        list: action.todos
      }
    case 'delById':
      return {
        ...state,
        list: state.list.filter((v) => v.id !== action.id)
      }
    case 'addTodo':
      return {
        ...state,
        list: [action.todo, ...state.list]
      }
    case 'changeDoneById':
      return {
        ...state,
        list: state.list.map((item) => (item.id === action.id ? { ...item, done: !item.done } : item))
      }
    case 'clearDone':
      return {
        ...state,
        list: state.list.filter((v) => !v.done)
      }
    case 'checkAllTodo':
      return {
        ...state,
        list: state.list.map((item) => ({ ...item, done: action.ckecked }))
      }
    case 'changeType':
      return {
        ...state,
        type: action.payload
      }
    default:
      return state
  }
}

// 创建仓库实例
const store = createStore(reducer)

// 导出仓库实例
export default store
